<template>
  <div class="personnel-management">
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="80%"
      :close-on-click-modal="false"
      :before-close="handleBeforeClose"
    >
      <div>
        <el-form>
          <el-form-item style="float: right;">
            <el-button
              type="primary"
              icon="el-icon-plus"
              class="search-right"
              @click="handleAdd"
            >
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
        ref="table"
        :data="tableData"
        style="width: 100%"
        border
        height="400"
      >
        <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center"
        />

        <el-table-column
          prop="UserName"
          label="用户名"
          min-width="120"
        />

        <el-table-column
          prop="JobType"
          label="用户岗位类型"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ getJobTypeText(scope.row.JobType) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="IsWork"
          label="主持工作"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ scope.row.IsWork === '1' ? '是' : '否' }}
          </template>
        </el-table-column>

        <el-table-column
          prop="JobRespon"
          label="工作职责"
          min-width="180"
        />

        <el-table-column
          label="操作"
          width="180"
          fixed="right"
          align="center"
        >
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button
                :disabled="!(scope.row.lingma_sys_params.e.length>0)"
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>

              <el-button

                type="text"
                size="mini"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部按钮区域 -->
      <div class="footer-buttons">
        <div class="footer-right">
          <el-button
            icon="el-icon-close"
            @click="handleClose"
          >
            关闭
          </el-button>
        </div>
      </div>
    </el-dialog>
    <Adduser
      :user-visible="AddUserVisible"
      :userdj="userdj"
      :userlist="userlist"
      :title="usertitle"
      :depjobrow="depjobrow"
      @close="handleAddUserClose"
      @refresh="refresh"
    />
  </div>
</template>

<script>
import { GetData,BatchTableOperateRequestByCRUD } from '@/api/Hr';
import Adduser from './add-user.vue'
export default {
   name: 'UserSet', // 给父组件起个名字
      components: {
        Adduser
      },
    props: {
        dialogVisible: {
            type: Boolean,
            default: false
        },
        title: {
            type: String,
            default: ''
        },
        jobdep: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            dialogTitle: '人员设置',
            tableData: [],
            selectedRows: [],
            loading: false,
            AddUserVisible:false,
            userdj:[],
            depjobrow:{},
            jobtype: [],
            userlist:{},
            usertitle:'',
            refreshState:false
            
        };
    },
    watch: {
        dialogVisible(val) {
            if (val) {
                this.loadData()
            }
        }
    },
    methods: {
        async loadData() {
            try {
              this.refreshState=false
              console.log(this.jobdep)
                this.jobtype = await this.getjobtype()
                const data = {
                    "Table": [
                        {
                            "Name": "Base_User_DJ",
                            "Type": "数据库表",
                            "DbName": "task_demo",
                            "DISTINCT": true,
                            "Filter": {
                                "Type": "and",
                                "Filters": [
                                    {
                                        "Type": "and",
                                        "Filters": [
                                            {
                                                "Type": "cond",
                                                "Field": "DepID",
                                                "Operator": "equal",
                                                "Value": null,
                                                "ValueFun": {
                                                    "Type": "GetConstValue",
                                                    "Value": this.jobdep.DepID
                                                }
                                            },
                                            {
                                                "Type": "cond",
                                                "Field": "JobId",
                                                "Operator": "equal",
                                                "Value": null,
                                                "ValueFun": {
                                                    "Type": "GetConstValue",
                                                    "Value": this.jobdep.JobId
                                                }
                                            }
                                        ]
                                    }
                                ]
                            }
                        }
                    ]
                }
                GetData(data, 'DA242D6EF89B69A7ED5D2728408833AB').then(res => {
                    this.tableData = res.Result.data.Items
                    this.loading = false;
                }).catch(err => {
                    this.loading = false;
                    this.$message.error('加载数据失败');
                });

            } catch (error) {

                this.$message.error('加载数据失败');
            } finally {
                this.loading = false;
            }
        },
        async getjobtype() {
            try {
                const res = await GetData({
                    Table: [
                        {
                            Name: "pt_JobTypeUser",
                            Type: "字典",
                            DbName: "",
                            DISTINCT: true,


                        }
                    ]
                }, 'DA242D6EF89B69A7ED5D2728408833AB');
               
                const jobtype = res.Result.data.Items.map(item => {
                    return {
                        val: item.val,
                        txt: item.txt
                    };
                });
                return jobtype;
            } catch (error) {
                console.log(error);
            }
        },
        getJobTypeText(value) {
           const found = this.jobtype.find(item => item.val === value.toString());
          return found ? found.txt : '未知类型';
        },
        handleClose() {

            this.$emit('close',this.refreshState);
        },
        handleBeforeClose(){
           this.$emit('close', this.refreshState);
        },

        // 新增行
        handleAdd() {
          this.usertitle='新增人员'
          this.userdj=this.tableData
          this.depjobrow=this.jobdep
          this.AddUserVisible = true;
        },

        // 编辑行
        handleEdit(row) {
        this.usertitle='编辑人员'
          this.userdj=this.tableData
          this.userlist=row 
          this.AddUserVisible = true;
        },
        handleDelete(row){
           this.$confirm('确定要删除这条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const data = [{
        TableName: 'task_demo@Base_User_DJ', // 根据实际表名调整
        CrudModel: {
          Added: [],
          Changed: [],
          Deleted: [{
            rowid: row.rowid
          }]
        }
      }];
      const res = await BatchTableOperateRequestByCRUD(data, 'DA242D6EF89B69A7ED5D2728408833AB');
      if (res.Code===200) {
        this.$message.success('删除成功');
        this.loadData()
        this.refreshState=true
      } else {
        this.$message.error('删除失败');
      }
    } catch (error) {
      console.log(error);
      this.$message.error('删除失败');
    }
  }).catch(() => {
    this.$message.info('已取消删除');
  });
        },
        handleAddUserSuccess(res) {
            this.$message.success('新增成功');
            this.loadData()
        },
        handleAddUserClose() {          
            this.AddUserVisible = false;
        },
        refresh(){
           this.AddUserVisible = false;
           this.loadData()
           this.refreshState=true
        }

    }
}
</script>

<style scoped>
/* 对话框标题左对齐 */
::v-deep .el-dialog__header {
  text-align: left;
}
.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
}

.header-left,
.header-right {
    display: flex;
    gap: 10px;
}

.search-container {
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 4px;
    position: relative;
}

.search-container .el-form-item {
    margin-bottom: 0;
}


/* 底部按钮区域 */
.footer-buttons {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
}

.footer-right {
    display: flex;
    gap: 10px;
}

.action-buttons {
    display: flex;
    gap: 5px;
    justify-content: center;
}

.no-data {
    text-align: center;
    padding: 40px 0;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
}

/* 表格样式优化 */
.el-table {
    font-size: 14px;
}

.el-table .el-input,
.el-table .el-select,
.el-table .el-textarea {
    width: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .search-container .el-form-item {
        margin-bottom: 10px;
    }

    .search-right {
        position: static;
        transform: none;
        margin-top: 10px;
        display: flex;
        justify-content: flex-end;
    }
}
</style>